'use client'

import { useState, useEffect } from 'react'
import { Card, Row, Col, Button, Empty, Spin, message, Tag } from 'antd'
import { AppstoreOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons'
import Link from 'next/link'
import ProductSearchFilter from '../../components/ProductSearchFilter'

// 产品类型常量
const PRODUCT_TYPES = {
    WEBSITE: 'website',
    APP: 'app'
}

export default function ProductsPage() {
    const [products, setProducts] = useState([])
    const [loading, setLoading] = useState(true)
    const [searchTerm, setSearchTerm] = useState('')
    const [filterType, setFilterType] = useState('all')
    const [sortBy, setSortBy] = useState('created_at')

    // 获取产品列表
    const fetchProducts = async () => {
        try {
            setLoading(true)
            // 构建查询参数
            const params = new URLSearchParams()
            if (searchTerm) params.append('search', searchTerm)
            if (filterType !== 'all') params.append('type', filterType)
            if (sortBy) {
                params.append('sortBy', sortBy)
                params.append('sortOrder', sortBy === 'view_count' ? 'desc' : 'desc')
            }

            const response = await fetch(`/api/products?${params.toString()}`)
            const data = await response.json()

            if (process.env.NODE_ENV === 'development') {
                console.log('API响应数据:', data)
            }

            if (data.success) {
                // API返回的数据结构是 { data: { products: [...] } }
                const productsData = Array.isArray(data.data?.products) ? data.data.products : []
                setProducts(productsData)

                if (process.env.NODE_ENV === 'development') {
                    console.log('设置的产品数据:', productsData)
                }
            } else {
                console.warn('获取产品列表失败:', data.error)
                message.error('获取产品列表失败')
                setProducts([]) // 确保设置为空数组
            }
        } catch (error) {
            console.warn('获取产品列表错误:', error)
            message.error('网络错误，请稍后重试')
            setProducts([]) // 确保在错误时也设置为空数组
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        fetchProducts()
    }, [searchTerm, filterType, sortBy])

    // 过滤产品 - 确保products是数组
    const filteredProducts = Array.isArray(products) ? products.filter(product => {
        const matchesSearch = product.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            product.description?.toLowerCase().includes(searchTerm.toLowerCase())
        const matchesType = filterType === 'all' || product.type === filterType
        return matchesSearch && matchesType
    }) : []

    // 获取产品类型标签颜色
    const getTypeColor = (type) => {
        switch (type) {
            case PRODUCT_TYPES.WEBSITE:
                return 'blue'
            case PRODUCT_TYPES.APP:
                return 'green'
            default:
                return 'default'
        }
    }

    // 获取产品类型显示名称
    const getTypeName = (type) => {
        switch (type) {
            case PRODUCT_TYPES.WEBSITE:
                return '网站'
            case PRODUCT_TYPES.APP:
                return '应用'
            default:
                return '未知'
        }
    }

    return (
        <div className="p-8">
            <div className="max-w-7xl mx-auto">
                {/* 页面标题 */}
                <div className="text-center mb-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-4">
                        <AppstoreOutlined className="mr-3" />
                        产品展示
                    </h1>
                    <p className="text-gray-600 text-lg">
                        浏览平台上的所有医学影像处理工具和应用
                    </p>
                </div>

                {/* 搜索和筛选 */}
                <ProductSearchFilter
                    searchTerm={searchTerm}
                    onSearchChange={setSearchTerm}
                    filterType={filterType}
                    onFilterChange={setFilterType}
                    sortBy={sortBy}
                    onSortChange={setSortBy}
                    resultCount={filteredProducts.length}
                    searchPlaceholder="搜索产品名称或描述..."
                />

                {/* 产品列表 */}
                {loading ? (
                    <div className="text-center py-12">
                        <Spin size="large" />
                        <p className="mt-4 text-gray-500">加载中...</p>
                    </div>
                ) : filteredProducts.length === 0 ? (
                    <Empty
                        description={
                            searchTerm || filterType !== 'all'
                                ? "没有找到符合条件的产品"
                                : "暂无产品，成为第一个上传产品的用户吧！"
                        }
                        className="py-12"
                    >
                        {(!searchTerm && filterType === 'all') && (
                            <Link href="/upload">
                                <Button type="primary" size="large">
                                    上传产品
                                </Button>
                            </Link>
                        )}
                    </Empty>
                ) : (
                    <Row gutter={[24, 24]}>
                        {filteredProducts.map((product) => (
                            <Col xs={24} sm={12} lg={8} xl={6} key={product.id}>
                                <Card
                                    hoverable
                                    className="h-full"
                                    cover={
                                        product.thumbnail_url ? (
                                            <div className="h-48 overflow-hidden">
                                                {/* eslint-disable-next-line @next/next/no-img-element */}
                                                <img
                                                    alt={product.title}
                                                    src={product.thumbnail_url}
                                                    className="w-full h-full object-cover"
                                                />
                                            </div>
                                        ) : (
                                            <div className="h-48 bg-gray-100 flex items-center justify-center">
                                                <AppstoreOutlined className="text-4xl text-gray-400" />
                                            </div>
                                        )
                                    }
                                    actions={[
                                        <Link href={`/product/${product.id}`} key="view">
                                            <Button type="text" icon={<EyeOutlined />}>
                                                查看详情
                                            </Button>
                                        </Link>,
                                        product.type === PRODUCT_TYPES.WEBSITE ? (
                                            <Button
                                                type="text"
                                                icon={<EyeOutlined />}
                                                onClick={() => window.open(product.url, '_blank')}
                                                key="visit"
                                            >
                                                访问网站
                                            </Button>
                                        ) : (
                                            <Button
                                                type="text"
                                                icon={<DownloadOutlined />}
                                                onClick={() => window.open(product.file_url, '_blank')}
                                                key="download"
                                            >
                                                下载
                                            </Button>
                                        )
                                    ]}
                                >
                                    <Card.Meta
                                        title={
                                            <div className="flex items-center justify-between">
                                                <span className="truncate">{product.title}</span>
                                                <Tag color={getTypeColor(product.type)} className="ml-2">
                                                    {getTypeName(product.type)}
                                                </Tag>
                                            </div>
                                        }
                                        description={
                                            <div>
                                                <p className="text-gray-600 line-clamp-3 mb-2">
                                                    {product.description}
                                                </p>
                                                <div className="text-xs text-gray-400 flex justify-between items-center">
                                                    <span>{new Date(product.created_at).toLocaleDateString('zh-CN')}</span>
                                                    <span className="flex items-center">
                                                        <EyeOutlined className="mr-1" />
                                                        {product.view_count || 0}
                                                    </span>
                                                </div>
                                            </div>
                                        }
                                    />
                                </Card>
                            </Col>
                        ))}
                    </Row>
                )}
            </div>
        </div>
    )
}